package com.dllo.lanou.cookapp.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;

import com.dllo.lanou.cookapp.R;

/**
 * Created by xijinhua on 2016/3/24.
 */
public class LoadListView extends ListView implements AbsListView.OnScrollListener {
    //添加footView
    private View footView;
    private int totalItemCount;//总数量
    private int lastVisibleItem;//最后一个item
    private ILoadListener listener;

    private boolean isLoading;//正在加载

    private void initView(Context context) {
        LayoutInflater inflater = LayoutInflater.from(context);
        footView = inflater.inflate(R.layout.foot_listview, null);
        footView.findViewById(R.id.load_layout).setVisibility(View.GONE);
        this.addFooterView(footView);
        this.setOnScrollListener(this);
    }

    public LoadListView(Context context) {
        super(context);
        initView(context);
    }

    public LoadListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public LoadListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        this.lastVisibleItem = firstVisibleItem + visibleItemCount;
        this.totalItemCount = totalItemCount;
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (totalItemCount == lastVisibleItem && scrollState == SCROLL_STATE_IDLE) {
            //加载更多
            if (!isLoading) {
                isLoading = true;
                footView.findViewById(R.id.load_layout).setVisibility(View.VISIBLE);
                listener.onLoad();
            }

        }
    }

    public void  loadComplete(){
        isLoading =false;
        footView.findViewById(R.id.load_layout).setVisibility(View.GONE);
    }

    //加载更过的毁掉接口
    public interface ILoadListener {
        public void onLoad();
    }

    public void setInterface(ILoadListener listener) {
        this.listener = listener;
    }


}
